// 拖拽功能模块

import { handleDragOver } from './eventHandler.js';
import dataManager, { STORAGE_KEY, BACKUP_KEY } from './dataManager.js';

// 设置拖拽事件
export function setupDragAndDrop() {
    const container = document.getElementById('icon-container');
    if (!container) return;
    
    // 使用事件委托而不是为每个元素添加事件监听器
    // 清除现有事件
    container.removeEventListener('dragover', handleContainerDragOver);
    container.removeEventListener('dragstart', handleDragStart);
    container.removeEventListener('dragend', handleDragEnd);
    container.removeEventListener('dragenter', handleDragEnter);
    container.removeEventListener('dragleave', handleDragLeave);
    container.removeEventListener('drop', handleDrop);
    
    // 添加事件委托
    container.addEventListener('dragover', handleContainerDragOver);
    container.addEventListener('dragstart', function(e) {
        const draggable = e.target.closest('.draggable');
        const textContent = draggable?.querySelector('.text-xs')?.textContent;
        if (draggable && !textContent?.includes('添加导航') && !textContent?.includes('系统设置')) {
            handleDragStart.call(draggable, e);
        }
    });
    container.addEventListener('dragend', function(e) {
        const draggable = e.target.closest('.draggable');
        if (draggable && window.dragSource === draggable) {
            handleDragEnd.call(draggable, e);
        }
    });
    container.addEventListener('dragenter', function(e) {
        const draggable = e.target.closest('.draggable');
        const textContent = draggable?.querySelector('.text-xs')?.textContent;
        if (draggable && !textContent?.includes('添加导航') && !textContent?.includes('系统设置')) {
            handleDragEnter.call(draggable, e);
        }
    });
    container.addEventListener('dragleave', function(e) {
        const draggable = e.target.closest('.draggable');
        if (draggable) {
            handleDragLeave.call(draggable, e);
        }
    });
    container.addEventListener('drop', function(e) {
        // 注意：在drop事件中，e.target可能是容器而不是draggable元素
        // 我们需要确保handleDrop在正确的元素上下文中被调用
        const draggable = window.dragOverElement || e.target.closest('.draggable');
        if (draggable) {
            handleDrop.call(draggable, e);
        }
    });
    
    // 设置可拖动属性
    const draggables = document.querySelectorAll('.draggable');
    draggables.forEach(item => {
        // 确保不是"添加导航"按钮
        if (!item.querySelector('.text-xs')?.textContent?.includes('添加导航')) {
            item.draggable = true;
        } else {
            item.draggable = false;
        }
    });
    
    // 重新高亮可放置的标签页
    unhighlightTabsForDrop();
}

// 拖拽事件处理函数
export function handleDragStart(e) {
    window.dragSource = this;
    e.stopPropagation();
    
    // 使用CSS类来统一拖拽样式，避免JavaScript和CSS样式冲突
    this.classList.add('dragging');
    
    e.dataTransfer.effectAllowed = 'move';
    
    // 存储拖动的元素索引和当前标签页
    const dragData = {
        index: this.dataset.index,
        tab: window.currentTab
    };
    
    // 如果是ALL页，添加源标签页信息
    if (window.currentTab === 'ALL' && this.dataset.sourceTab) {
        dragData.sourceTab = this.dataset.sourceTab;
        dragData.fromAll = true;
        
        // 在ALL页，获取原始索引
        const index = parseInt(this.dataset.index);
        if (!isNaN(index) && index >= 0 && window.iconsToRender && index < window.iconsToRender.length) {
            const originalIndex = window.iconsToRender[index].originalIndex;
            if (typeof originalIndex === 'number') {
                dragData.index = originalIndex;
            }
        }
    }
    
    // 设置拖拽数据
    try {
        const jsonData = JSON.stringify(dragData);
        e.dataTransfer.setData('text/plain', jsonData);
    } catch (err) {
            // 设置拖拽数据失败，忽略错误
        }
    
    highlightTabsForDrop();
    return true;
}

export function handleDragEnd(e) {
    if (window.dragSource) {
        // 移除拖拽样式类
        window.dragSource.classList.remove('dragging');
    }
    
    // 清除所有突出显示
    unhighlightTabsForDrop();
    
    // 清除所有拖动效果
    clearAllDragStyles();
    
    window.dragSource = null;
    window.dragOverElement = null;
}

export function handleContainerDragOver(e) {
    e.preventDefault();
}

export function handleDragEnter(e) {
    e.preventDefault();
    if (this !== window.dragSource) {
        this.classList.add('drop-indicator');
        // 设置当前拖拽目标元素
        window.dragOverElement = this;
    }
}

export function handleDragLeave(e) {
    // 增加子元素检测：当鼠标移动到子元素时不触发状态变化
    if (e.relatedTarget && this.contains(e.relatedTarget)) {
        return;
    }
    
    this.classList.remove('drop-indicator');
    // 只有当离开的元素是当前拖拽目标时才清除
    if (window.dragOverElement === this) {
        window.dragOverElement = null;
    }
}

export function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();
    
    if (!window.dragSource) {
        return false;
    }
    
    try {
        // 获取拖动和目标的数据
        let srcData;
        try {
            srcData = JSON.parse(e.dataTransfer.getData('text/plain'));
        } catch (error) {
            // 无法解析拖拽数据，忽略
            return false;
        }
        
        // 处理ALL页面的拖拽
        if (srcData.fromAll && srcData.sourceTab) {
            // 从ALL页拖动到其他标签页
            if (srcData.tab === 'ALL' && window.currentTab !== 'ALL') {
                // 获取源标签页中的图标
                const sourceIcon = window.data.icons[srcData.sourceTab][srcData.index];
                if (sourceIcon) {
                    // 检查URL是否已存在于目标标签页
                    const isDuplicate = window.data.icons[window.currentTab].some(icon => icon.url === sourceIcon.url);
                    
                    if (isDuplicate) {
                        if (typeof window.showToast === 'function') {
                            window.showToast(`目标标签页"${window.currentTab}"已包含此URL`);
                        }
                        return false;
                    }
                    
                    // 移动图标而不是复制
                    const iconToMove = {...sourceIcon};
                    
                    // 从源标签页移除
                    window.data.icons[srcData.sourceTab].splice(srcData.index, 1);
                    
                    // 添加到当前标签页
                    window.data.icons[window.currentTab].push(iconToMove);
                    
                    if (typeof window.renderIcons === 'function') {
                        window.renderIcons(window.data, window.currentTab);
                    }
                    if (typeof window.showToast === 'function') {
                        window.showToast(`已移动图标到"${window.currentTab}"`);
                    }
                }
                return false;
            }
        }
        
        // 处理跨标签页拖拽 - 使用统一的移动函数
        if (srcData.tab !== window.currentTab) {
            // 调用统一的跨标签页移动函数
            if (typeof window.moveIconBetweenTabs === 'function') {
                const success = window.moveIconBetweenTabs(srcData, window.currentTab);
                if (success && typeof window.renderIcons === 'function') {
                    window.renderIcons(window.data, window.currentTab);
                }
                return success;
            } else {
                return false;
            }
        }
        
        // 常规同标签页内拖拽
        if (srcData.tab === window.currentTab) {
            let srcIndex = parseInt(srcData.index);
            const destElement = window.dragOverElement;
            let destIndex = destElement ? parseInt(destElement.dataset.index) : parseInt(this.dataset.index);
            
            // 确保索引有效
            if (!isNaN(srcIndex) && !isNaN(destIndex) && 
                srcIndex >= 0 && destIndex >= 0 && 
                srcIndex < window.data.icons[window.currentTab].length && 
                destIndex < window.data.icons[window.currentTab].length) {
                
                // 只有当源索引和目标索引不同时才进行移动
                if (srcIndex !== destIndex) {
                    // 从数组中移除并插入到新位置
                    const icons = window.data.icons[window.currentTab];
                    
                    // 正确处理元素在数组中的移动
                    if (srcIndex < destIndex) {
                        const [movedItem] = icons.splice(srcIndex, 1);
                        icons.splice(destIndex, 0, movedItem);
                    } else {
                        const movedItem = icons[srcIndex];
                        icons.splice(destIndex, 0, movedItem);
                        icons.splice(srcIndex + 1, 1);
                    }
                    
                    // 更新全局iconsToRender数组（用于ALL页面）
                    if (window.currentTab === 'ALL' && window.iconsToRender) {
                        window.iconsToRender = [];
                        for (const tab in window.data.icons) {
                            if (tab !== 'ALL' && Array.isArray(window.data.icons[tab])) {
                                const taggedIcons = window.data.icons[tab].map((icon, originalIndex) => ({
                                    ...icon,
                                    sourceTab: tab,
                                    originalIndex: originalIndex
                                }));
                                window.iconsToRender = window.iconsToRender.concat(taggedIcons);
                            }
                        }
                    }
                    
                    // 保存数据并更新UI
                    const saveSuccess = window.dataManager?.saveData?.(window.data);
                    if (saveSuccess) {
                        window.renderIcons?.(window.data, window.currentTab);
                    } else {
                        window.showToast?.('保存失败');
                    }
                }
            } else {
                // 索引无效
            }
        }
    } catch (error) {
        // 拖放操作失败，清理状态
        if (typeof window.showToast === 'function') {
            window.showToast('移动图标失败');
        }
    } finally {
        // 清除所有拖放状态
        clearAllDragStyles();
        unhighlightTabsForDrop();
        window.dragSource = null;
        window.dragOverElement = null;
    }
    
    return false;
}

// 触摸拖拽变量
let touchDragSource = null;
let touchStartX = 0;
let touchStartY = 0;
let touchLastX = 0;
let touchLastY = 0;
let touchDragging = false;
let touchPlaceholder = null;
let longPressTimeout = null;

// 触摸拖拽处理函数
export function handleTouchStart(e) {
    // 防止与滑动切换标签页冲突
    e.stopPropagation();
    
    // 记录起始位置
    touchStartX = e.touches[0].clientX;
    touchStartY = e.touches[0].clientY;
    touchLastX = touchStartX;
    touchLastY = touchStartY;
    
    // 设置长按触发拖拽
    longPressTimeout = setTimeout(() => {
        touchDragSource = this;
        touchDragging = true;
        
        // 创建视觉反馈
        this.classList.add('dragging');
        
        // 震动反馈（如果设备支持）
        if (navigator.vibrate) {
            navigator.vibrate(50);
        }
        
        // 显示拖拽提示
        if (typeof window.showToast === 'function') {
            window.showToast('拖动图标可更改位置');
        }
    }, 300); // 300ms长按触发
}

export function handleTouchMove(e) {
    if (!touchDragging || !touchDragSource) {
        // 如果移动超过一定距离，取消长按
        const diffX = Math.abs(e.touches[0].clientX - touchStartX);
        const diffY = Math.abs(e.touches[0].clientY - touchStartY);
        if (diffX > 10 || diffY > 10) {
            clearTimeout(longPressTimeout);
        }
        return;
    }
    
    // 阻止页面滚动
    e.preventDefault();
    
    // 更新拖拽元素位置
    const touchX = e.touches[0].clientX;
    const touchY = e.touches[0].clientY;
    
    // 计算移动距离
    const deltaX = touchX - touchLastX;
    const deltaY = touchY - touchLastY;
    
    // 更新元素位置
    const currentLeft = parseInt(touchDragSource.style.left || '0');
    const currentTop = parseInt(touchDragSource.style.top || '0');
    Object.assign(touchDragSource.style, {
        position: 'absolute',
        left: (currentLeft + deltaX) + 'px',
        top: (currentTop + deltaY) + 'px'
    });
    
    // 更新最后位置
    touchLastX = touchX;
    touchLastY = touchY;
    
    // 检测碰撞并显示放置位置
    const targetElement = findDropTarget(touchX, touchY);
    if (targetElement && targetElement !== touchDragSource) {
        document.querySelectorAll('.draggable').forEach(item => {
            item.classList.remove('drop-indicator');
        });
        targetElement.classList.add('drop-indicator');
    }
}

export function handleTouchEnd(e) {
    // 清除长按定时器
    clearTimeout(longPressTimeout);
    
    if (!touchDragging || !touchDragSource) return;
    
    // 阻止默认行为
    e.preventDefault();
    e.stopPropagation();
    
    // 查找放置目标
    const touchX = e.changedTouches[0].clientX;
    const touchY = e.changedTouches[0].clientY;
    const targetElement = findDropTarget(touchX, touchY);
    
    // 如果找到有效的放置目标，执行移动
    if (targetElement && targetElement !== touchDragSource) {
        const srcIndex = parseInt(touchDragSource.dataset.index);
        const destIndex = parseInt(targetElement.dataset.index);
        const icons = window.data.icons[window.currentTab];
        
        if (!isNaN(srcIndex) && !isNaN(destIndex) && 
            srcIndex >= 0 && destIndex >= 0 && 
            srcIndex < icons.length && destIndex < icons.length) {
            
            const [movedItem] = icons.splice(srcIndex, 1);
            icons.splice(destIndex, 0, movedItem);
            
            if (navigator.vibrate) {
                navigator.vibrate(30);
            }
        }
    }
    
    // 重置拖拽状态
    clearElementStyles(touchDragSource);
    touchDragSource.classList.remove('dragging');
    
    // 清除所有高亮并重新渲染
    clearAllDragStyles();
    window.renderIcons?.(window.data, window.currentTab);
    
    // 重置变量
    touchDragging = false;
    touchDragSource = null;
}

// 清除元素样式的辅助函数
function clearElementStyles(element) {
    if (!element) return;
    // 只清除触摸拖拽时设置的位置样式
    Object.assign(element.style, {
        position: '',
        left: '',
        top: ''
    });
}

// 清除所有拖拽样式的辅助函数
function clearAllDragStyles() {
    document.querySelectorAll('.draggable').forEach(item => {
        item.classList.remove('drop-indicator', 'dragging');
        clearElementStyles(item);
    });
}

// 查找放置目标
function findDropTarget(x, y) {
    // 获取所有可放置的元素
    const draggables = Array.from(document.querySelectorAll('.draggable'));
    
    // 过滤掉添加按钮和当前拖拽元素
    const validTargets = draggables.filter(item => {
        return item !== touchDragSource && 
                !item.querySelector('.text-xs')?.textContent?.includes('添加导航');
    });
    
    // 查找碰撞元素
    for (const target of validTargets) {
        const rect = target.getBoundingClientRect();
        if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
            return target;
        }
    }
    
    return null;
}

// 高亮所有标签页以指示可拖放
export function highlightTabsForDrop() {
    if (!window.data || window.data.tabs.length <= 1) return;
    
    document.querySelectorAll('.tab-btn').forEach(tab => {
        if (tab.dataset.tab !== window.currentTab) {
            tab.classList.add('pulse-animation');
        }
    });
}

// 取消高亮
export function unhighlightTabsForDrop() {
    document.querySelectorAll('.tab-btn').forEach(tab => {
        tab.classList.remove('pulse-animation', 'drop-hover');
    });
}

// 导出模块
export default {
    setupDragAndDrop,
    handleDragStart,
    handleDragEnd,
    handleContainerDragOver,
    handleDragEnter,
    handleDragLeave,
    handleDrop,
    handleTouchStart,
    handleTouchMove,
    handleTouchEnd,
    highlightTabsForDrop,
    unhighlightTabsForDrop
};